/**
 * 
 */   
package com.gson.inter;  

import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.xfire.client.Client;

import com.gson.db.MysqlDb;
import com.gson.model.ChResultInfo;
import com.gson.model.OrgInfo;
import com.gson.util.SaxParseUtil;
import com.gson.util.So114Util;
import com.gson.util.StringUtil;

/**   
 * @作者 Stone
 * @创建日期 2014-6-24 上午10:37:30
 * @版本 V1.0
 * @类说明
 */
public class So114Service {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		So114Service ss = new So114Service();
		
		System.out.println(ss.doSearch("苏州市 工商局"));
	}
	
	public String doSearch(String content) {
		String result = null;
		
		int index = content.indexOf(" ");
		String cityName = content.substring(0, index);// 城市名,暂不使用
		String cityRegion = getRegionCode(cityName);// 城市行政编码,暂截取后处理
		String strKeywords = content.substring(index+1, content.length());// 搜索关键字
		String pageSize = "10";// 每页数据条数
		String page = "1";// 页码
		String vm = "358239051178665";// 电话号码伪码,暂存
		
		if(StringUtils.isNotEmpty(cityRegion)) {
			
			String requestXml = getRequestXml(cityRegion, strKeywords, pageSize, page, vm);
			
			try {
				long startTime = System.currentTimeMillis();
				
				ChResultInfo resultInfo = seachChResult(requestXml);
				
				long endTime = System.currentTimeMillis();
				
				System.out.println("search cost==" + (endTime - startTime));
				
				if(resultInfo!=null) {
					List<OrgInfo> orgList = resultInfo.getOrgList();
					if(orgList!=null && orgList.size()>0) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < orgList.size(); i++) {
							// 设置Title
							sb.append(orgList.get(i).getCustomerName());
							sb.append("\r\n");
							
							if (StringUtils.isNotEmpty(orgList.get(i).getAddress())) {
								sb.append("地址：").append(orgList.get(i).getAddress());
								sb.append("\r\n");
							}
							
							String tel = orgList.get(i).getCustTelephone();
							tel = tel.replaceAll("[；;]", " ");
							if (StringUtils.isNotEmpty(tel)) {
								if(i == orgList.size()-1) {
									sb.append("电话：").append(tel);
								} else {
									sb.append("电话：").append(tel);
									sb.append("\r\n");
									sb.append("\r\n");
								}
							}
						}
						result = sb.toString();
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return result;
	}

	/**
	 * @param cityRegion
	 * @param strKeywords
	 * @param pageSize
	 * @param page
	 * @param vm
	 * @return
	 */
	private static String getRequestXml(String cityRegion, String strKeywords,
			String pageSize, String page, String vm) {
		StringBuilder sb = new StringBuilder("");
		sb.append("<RequestInfo>");
		sb.append("<region><![CDATA["+StringUtil.getMinRegion(cityRegion)+"]]></region>");
		sb.append("<content><![CDATA["+strKeywords+"]]></content>");
		//sb.append("<content><![CDATA["+strKeywords+"/n]]></content>"); //针对商家名称进行搜索
		if(page!=null){
			sb.append("<Page><![CDATA["+page+"]]></Page>");
		}
		if(pageSize!=null){
			sb.append("<PageSize><![CDATA["+pageSize+"]]></PageSize>");
		}
		sb.append("<deviceid><![CDATA["+vm+"]]></deviceid>");
		sb.append("</RequestInfo>");
		
		String requestXml = sb.toString();
		return requestXml;
	}
	
	private static String getRegionCode(String regionName) {
		String regionCode = "";
		
		MysqlDb db = new MysqlDb();
		Connection conn = null;
		
		String sql = "select REGION_CODE from j_region j where name = '{NAME}' or  short_name = '{NAME}' order by REGION_CODE desc";
		
		sql = sql.replace("{NAME}", regionName);
		try {
			ResultSet rs = db.search(sql);
			if(rs!=null) {
				while(rs.next()) {
					regionCode = rs.getString("REGION_CODE");
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return regionCode;
	}
	
	/*
	 * 调用trs搜索引擎接口
	 */
	public ChResultInfo seachChResult(String requestXml) {
		Client client;
		String resultXml = null;
		try {
			Map urlMap = So114Util.getUrlWsdl("ch_inter.xml");
			String endpoint = (String) urlMap.get("114SoUrl");
			String method = (String) urlMap.get("searchMethod");
			String name = (String) urlMap.get("name");
			String key = (String) urlMap.get("key");
			
			client = new Client(new URL(endpoint));
			Object[] results = client.invoke(method, new String[] {
					requestXml, name, key});
			resultXml = results[0].toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		SaxParseUtil sax = new SaxParseUtil();
		ChResultInfo resultInfo = sax.getSearchResult(resultXml);
		
		return resultInfo;
	}

}
